package com.csrcb.services;

import com.csrcb.constants.MyConstant;
import com.csrcb.entity.AccountInfo;
import com.csrcb.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
 * @Classname AssetService
 * @Date 2021/8/20 15:59
 * @Created by gangye
 */
@Service
@Slf4j
public class AssetService {
    @Autowired
    private OkHttpClient okHttpClient;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    public BigDecimal getAcctBal(int userId) throws IOException {
        String acctUrl = "http://localhost:8001/api/springbootDemoA/account/getAcctInfoByUserId";
        MediaType mediaType = MediaType.parse(MyConstant.APPLICATION_JSON_UTF8);
        RequestBody body = RequestBody.create(mediaType,MAPPER.writeValueAsString(new User(userId)));
        Request requestAcct = new Request.Builder().url(acctUrl).post(body).build();
        Response okHttpResponse = okHttpClient.newCall(requestAcct).execute();
        com.csrcb.tools.Response acctResponse = MAPPER.readValue(okHttpResponse.body().string(),com.csrcb.tools.Response.class);
        BigDecimal acctBal = BigDecimal.ZERO;
        if (acctResponse.isOK() && null != acctResponse.get("data")){
            List<AccountInfo> accountInfos = MAPPER.readValue(MAPPER.writeValueAsString(acctResponse.get("data")), MAPPER.getTypeFactory().constructParametricType(List.class, AccountInfo.class));
            acctBal = acctBal.add(accountInfos.stream().map(AccountInfo::getAvlBal).reduce(BigDecimal.ZERO, BigDecimal::add));
        }
        return acctBal;
    }

    public BigDecimal getFinacVal(){
        log.info("获取用户的理财份额");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            log.error("线程睡眠失败",e);
        }
        return new BigDecimal("10000");
    }

    public BigDecimal getFundMoneyVal(){
        log.info("获取用户的基金份额");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            log.error("线程睡眠失败",e);
        }
        return new BigDecimal("5000");
    }
}
